package com.xinxing.city.recovery;

import static android.content.Context.MODE_PRIVATE;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xinxing.city.recovery.entitys.BucketList;
import com.xinxing.city.recovery.entitys.BucketType;
import com.xinxing.city.recovery.entitys.Cabinet;
import com.xinxing.city.recovery.entitys.Catalogs;
import com.xinxing.city.recovery.entitys.Category;
import com.xinxing.city.recovery.entitys.KernelAction;
import com.xinxing.city.recovery.entitys.KernelActions;
import com.xinxing.city.recovery.entitys.MenuBean;
import com.xinxing.city.recovery.interfaces.ICallBackWeight;
import com.xinxing.city.recovery.interfaces.IDeviceKernel;
import com.xinxing.city.recovery.interfaces.IOrderManager;
import com.xinxing.city.recovery.interfaces.IRfidManager;
import com.xinxing.city.recovery.interfaces.ISerialSendReceiveData;
import com.xinxing.city.recovery.interfaces.ITtsService;
import com.xinxing.city.recovery.net.BaseTask;
import com.xinxing.city.recovery.net.RetroFactory;
import com.xinxing.city.recovery.serialport.SerialSendReceiveData;
import com.xinxing.city.recovery.ui.SetBucketActivity;
import com.xinxing.city.recovery.utils.Logger;
import com.xinxing.city.recovery.utils.SharedPreferencesUtils;
import com.xinxing.city.recovery.utils.SuUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DeviceKernel implements IDeviceKernel {
    private Context context;
    private IOrderManager orderManager;
    private ISerialSendReceiveData serialSendReceiveData;
    private APPRuntime appRuntime;
    private IRfidManager rfidManager;
    public static String deviceSerialNum;
    public ITtsService ttsService;
    @Override
    public void start(Context context) {
        this.context = context;
        serialSendReceiveData = DI.getInstance(ISerialSendReceiveData.class);
        if(!Constant.DEBUG) {
            serialSendReceiveData.start("/dev/ttyS3", 115200, this);
        }
        orderManager = DI.getInstance(IOrderManager.class);
        appRuntime = DI.getInstance(APPRuntime.class);
        rfidManager = DI.getInstance(IRfidManager.class);
        ttsService = DI.getInstance(ITtsService.class);

//
        if (!Constant.MOCK) {
            deviceSerialNum = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            rfidManager.start("/dev/ttyS4", 115200);
        } else {
//            deviceSerialNum = "123409886";
        }
//        anyWeight = appRuntime.getAnyWeight();
        initConfig();
        initMenu();
//        startGuardApp();
//        handler.post(runnable); //立刻就发
    }

    public Context getContent() {
        return context;
    }

    @Override
    public void stop() {
        serialSendReceiveData.stop();
        rfidManager.stop();
        handler.removeCallbacks(runnable);
    }

    @Override
    public IOrderManager getOrderManager() {
        return orderManager;
    }

    @Override
    public ISerialSendReceiveData getSerial() {
        return serialSendReceiveData;
    }

    Map<Integer, Long> anyWeight;
    int i = 1;

    @Override
    public void initConfig() {
        if (Constant.screenWidth == 800) {
            SharedPreferencesUtils.setParam(context,"piWeight1","24628");
            appRuntime.setPiWeight(1,24628L);
        }else{
            SharedPreferencesUtils.setParam(context,"piWeight1","24628");
            SharedPreferencesUtils.setParam(context,"piWeight2","11432");
            SharedPreferencesUtils.setParam(context,"piWeight3","13524");
            SharedPreferencesUtils.setParam(context,"piWeight4","24628");
            appRuntime.setPiWeight(1,24628L);
            appRuntime.setPiWeight(2,11432L);
            appRuntime.setPiWeight(3,13526L);
            appRuntime.setPiWeight(4,24628L);
        }
//        if(!Constant.DEBUG) {
//            for (int i = 1; i < 5; i++) {
//                String key = String.format("piWeight%d", i);
//                Log.e("ttt", "key   " + key);
//                String pi = (String) SharedPreferencesUtils.getParam(context, key, "0");
//                appRuntime.setPiWeight(i, Long.valueOf(pi));
//            }
//        }
        getCatalogs();
        String rfidcate = (String) SharedPreferencesUtils.getParam(context, "rfid", "");
        List<String> rfidCatas = null;
        Gson gson = new Gson();
        if (rfidcate.equals("")) {
            rfidCatas = new ArrayList<>();
        } else {
            Type cType = new TypeToken<List<String>>() {
            }.getType();
            rfidCatas = gson.fromJson(rfidcate, cType);
        }

        appRuntime.setNowRfid(rfidCatas);
    }

//    Handler handler = new Handler() {
//        @Override
//        public void handleMessage(@NonNull Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case 1:
//                    Log.e("num", "i .... " + i);
//                    if (i < 5) {
//                        serialSendReceiveData.getWeight(i, (num, weight) -> {
//                            anyWeight.put(num, weight);
//                            Logger.d("num：" + num + "  weight：" + weight);
//                            i++;
//                            handler.sendEmptyMessageDelayed(1, 50);
//                        });
//                    }
//                    break;
//            }
//        }
//    };

    @Override
    public APPRuntime getRuntime() {
        return appRuntime;
    }

    @Override
    public IRfidManager getRfid() {
        return rfidManager;
    }

    private void getCatalogs() {
        new BaseTask<List<Catalogs>>(context, RetroFactory.getJsonService().getCatalogs("1", true)).handleResponse(new BaseTask.ResponseListener<List<Catalogs>>() {
            @Override
            public void onSuccess(List<Catalogs> catalogs) {
                Map<String, Catalogs> map = new HashMap<>();

                appRuntime.setCatalogs(catalogs);
                Gson gson = new Gson();

                String cabinetStr = (String) SharedPreferencesUtils.getParam(context, "cabinet", "");
                if (cabinetStr.equals(""))
                    getHardware("");
                else {
                    Type cType = new TypeToken<Cabinet>() {
                    }.getType();
                    Cabinet cabinet = gson.fromJson(cabinetStr, cType);

                    String bucket = (String) SharedPreferencesUtils.getParam(context, "bucket", "");
                    Type bListType = new TypeToken<List<BucketType>>() {
                    }.getType();
                    List<BucketType> bucketTypes = gson.fromJson(bucket, bListType);
                    for (Catalogs category : catalogs) {

                        map.put(category.getCode(), category);
                    }
                    List<BucketType> bucketLists = new ArrayList<>();
                    Map<String, Integer> numMap = new HashMap<>();
                    if (bucketTypes != null) {
                        for (BucketType bucketType : bucketTypes) {
                            Catalogs catalogs1 = map.get(bucketType.getRecycleCataCode());
                            if (catalogs1 != null) {
                                if (numMap.get(bucketType.getRecycleCataCode()) != null) {
                                    numMap.put(bucketType.getRecycleCataCode(), numMap.get(bucketType.getRecycleCataCode() + 1));
                                } else {
                                    numMap.put(bucketType.getRecycleCataCode(), 1);
                                }

                                bucketType.setIcon(catalogs1.getIcon());
                                bucketType.setDefaultPkgPrice(catalogs1.getDefaultPkgPrice());
                                bucketType.setUnitName(catalogs1.getUnitName());
                                if (Constant.screenWidth == 800) {
                                    if (bucketType.getRecycleCataName().equals("全品类")) {
                                        bucketType.setNum(1);
                                    }
                                } else {
                                    Log.e("TTT", "品类1：" + bucketType.getRecycleCataName());
                                    if (bucketType.getRecycleCataName().equals("纸类")) {
                                        bucketType.setNum(1);
                                    } else if (bucketType.getRecycleCataName().contains("金属")) {
                                        bucketType.setNum(2);
                                    } else if (bucketType.getRecycleCataName().equals("塑料类")) {
                                        bucketType.setNum(3);
                                    } else if (bucketType.getRecycleCataName().equals("全品类")) {
                                        bucketType.setNum(4);
                                    }
                                }
                                bucketLists.add(bucketType);
                            }
                        }
                    }

                    String categoryStr = (String) SharedPreferencesUtils.getParam(context, "set_category", "");
                    if (categoryStr.equals("")) {
                        List<Catalogs> catalogsList = new ArrayList<>();
                        for (Catalogs category : catalogs) {
                            if (numMap.get(category.getCode()) != null) {
                                category.setNum(numMap.get(category.getCode()));
                            }
                            catalogsList.add(category);

                        }
                        SharedPreferencesUtils.setParam(context, "set_category", gson.toJson(catalogsList));
                        appRuntime.setCatalogs(catalogsList);
                    }
                    SharedPreferencesUtils.setParam(context, "bucket", gson.toJson(bucketLists));
                    appRuntime.setBuckes(bucketLists);
                    appRuntime.setCabinet(cabinet);
                    for(int i =0;i<bucketTypes.size();i++){

                        if(bucketTypes.get(i).getName()!=null&&bucketTypes.get(i).getName().equals("纸类")){
                            bucketTypes.get(i).setCompressStatus("00");
                            SetBaseView.buckets = bucketTypes;
                            SharedPreferencesUtils.setParam(context, "bucket", gson.toJson(bucketTypes));
                        }
                    }
                    EventBus.getDefault().post(new KernelAction(KernelActions.INIT_FINISH, null));

                }
            }

            @Override
            public void onFail() {
                initConfig();
                Log.e("ERROR", "失败");
            }
        });
    }

    private void getHardware(String code) {
        new BaseTask<List<Category>>(context, RetroFactory.getJsonService().getHardwareRegist(code, deviceSerialNum)).handleResponse(new BaseTask.ResponseListener<List<Category>>() {
            @Override
            public void onSuccess(List<Category> categories) {
                if (categories != null) {
//                    Gson gson = new Gson();
//                    SharedPreferencesUtils.setParam(context, "category", gson.toJson(categories));
                    String cabinetCode = "";
                    for (Category category : categories) {
                        if (category.getCabinetCode() != null && !category.getCabinetCode().equals("")) {
                            cabinetCode = category.getCabinetCode();
                            break;
                        }
                    }
                    if (!cabinetCode.equals("")) {
                        getCabinet(cabinetCode);
                    } else {

                        Toast.makeText(context, "未获取到回收柜信息，请先设置", Toast.LENGTH_LONG).show();
                    }
                }

            }

            @Override
            public void onFail() {
                Log.e("ERROR", "失败");
            }
        });
    }

    private void getBucket(String code) {
        new BaseTask<BucketList>(context, RetroFactory.getJsonService().getBucket("", "", code)).handleResponse(new BaseTask.ResponseListener<BucketList>() {

            @Override
            public void onSuccess(BucketList bucketList) {
                if (bucketList != null && bucketList.getInfos() != null) {
                    Gson gson = new Gson();
                    List<Catalogs> catalogs = appRuntime.getCatalogs();
                    Map<String, Catalogs> map = new HashMap<>();
                    for (Catalogs category : catalogs) {
                        map.put(category.getCode(), category);
                    }


                    List<BucketType> bucketLists = new ArrayList<>();
                    Map<String, Integer> numMap = new HashMap<>();
                    for (BucketType bucketType : bucketList.getInfos()) {
                        Catalogs catalogs1 = map.get(bucketType.getRecycleCataCode());
                        if (catalogs1 != null) {
                            if (numMap.get(bucketType.getRecycleCataCode()) != null) {
                                numMap.put(bucketType.getRecycleCataCode(), numMap.get(bucketType.getRecycleCataCode() + 1));
                            } else {
                                numMap.put(bucketType.getRecycleCataCode(), 1);
                            }
                            bucketType.setIcon(catalogs1.getIcon());
                            bucketType.setDefaultPkgPrice(catalogs1.getDefaultPkgPrice());
                            bucketType.setUnitName(catalogs1.getUnitName());
                            if (Constant.screenWidth == 800) {
                                if (bucketType.getRecycleCataName().equals("全品类")) {
                                    bucketType.setNum(1);
                                }
                            } else {
                                Log.e("TTT", "品类2：" + bucketType.getRecycleCataName());
                                if (bucketType.getRecycleCataName().equals("纸类")) {
                                    bucketType.setNum(1);
                                } else if (bucketType.getRecycleCataName().contains("金属")) {
                                    bucketType.setNum(2);
                                } else if (bucketType.getRecycleCataName().equals("塑料类")) {
                                    bucketType.setNum(3);
                                } else if (bucketType.getRecycleCataName().equals("全品类")) {
                                    bucketType.setNum(4);
                                }
                            }
                            bucketLists.add(bucketType);
                        }
                    }
                    String categoryStr = (String) SharedPreferencesUtils.getParam(context, "set_category", "");
                    if (categoryStr.equals("")) {
                        List<Catalogs> catalogsList = new ArrayList<>();
                        for (Catalogs category : catalogs) {
                            if (numMap.get(category.getCode()) != null) {
                                category.setNum(numMap.get(category.getCode()));
                            }
                            catalogsList.add(category);

                        }
                        SharedPreferencesUtils.setParam(context, "set_category", gson.toJson(catalogsList));
                        appRuntime.setCatalogs(catalogsList);
                    }
                    SharedPreferencesUtils.setParam(context, "bucket", gson.toJson(bucketLists));
                    appRuntime.setBuckes(bucketLists);

                    EventBus.getDefault().post(new KernelAction(KernelActions.INIT_FINISH, null));
                }
            }

            @Override
            public void onFail() {
                Log.e("ERROR", "失败");
            }
        });
    }

    private void getCabinet(String code) {
        new BaseTask<Cabinet>(context, RetroFactory.getJsonService().getRecyclingCabinet(code)).handleResponse(new BaseTask.ResponseListener<Cabinet>() {

            @Override
            public void onSuccess(Cabinet cabinet) {
                if (cabinet != null) {
                    Gson gson = new Gson();

                    SharedPreferencesUtils.setParam(context, "cabinet", gson.toJson(cabinet));
                    getBucket(code);
                    appRuntime.setCabinet(cabinet);
                }
            }

            @Override
            public void onFail() {

            }
        });
    }

    //生成初始化栏目列表
    @Override
    public void initMenu() {
        Gson gson = new Gson();


        String menu = (String) SharedPreferencesUtils.getParam(context, "menu_list", "");
        Log.e("菜单信息", menu);
        if (menu.equals("")) {
//            List<MenuBean> menuList = new ArrayList<>();
//
//            MenuBean menuBean1 = new MenuBean();
//            menuBean1.setCode("smjt");
//            menuBean1.setTitle("扫码交投");
//            menuBean1.setImage(R.mipmap.menu_1);
//            menuList.add(menuBean1);
//
//            MenuBean menuBean2 = new MenuBean();
//            menuBean2.setCode("rlsbjt");
//            menuBean2.setTitle("人脸识别交投");
//            menuBean2.setImage(R.mipmap.menu_2);
//            menuList.add(menuBean2);
//
//            MenuBean menuBean3 = new MenuBean();
//            menuBean3.setCode("sjhjt");
//            menuBean3.setTitle("手机号交投");
//            menuBean3.setImage(R.mipmap.menu_3);
//            menuList.add(menuBean3);
//
//            MenuBean menuBean4 = new MenuBean();
//            menuBean4.setCode("ickjt");
//            menuBean4.setTitle("IC卡交投");
//            menuBean4.setImage(R.mipmap.menu_4);
//            menuList.add(menuBean4);
//
//            MenuBean menuBean5 = new MenuBean();
//            menuBean5.setCode("smqh");
//            menuBean5.setTitle("扫码取货");
//            menuBean5.setImage(R.mipmap.menu_5);
//            menuList.add(menuBean5);
//
//
//            MenuBean menuBean6 = new MenuBean();
//            menuBean6.setCode("sz");
//            menuBean6.setTitle("设置");
//            menuBean6.setImage(R.mipmap.menu_7);
//            menuList.add(menuBean6);
//            SharedPreferencesUtils.setParam(context, "menu_list", gson.toJson(menuList));


            List<MenuBean> menuList = new ArrayList<>();

            MenuBean menuBean1 = new MenuBean();
            menuBean1.setCode("smjt");
            menuBean1.setTitle("扫码交投");
            menuBean1.setImage(R.mipmap.menu_1);
            menuList.add(menuBean1);

            MenuBean menuBean2 = new MenuBean();
            menuBean2.setCode("smqh");
            menuBean2.setTitle("扫码取货");
            menuBean2.setImage(R.mipmap.menu_5);
            menuList.add(menuBean2);

            MenuBean menuBean3 = new MenuBean();
            menuBean3.setCode("sz");
            menuBean3.setTitle("设置");
            menuBean3.setImage(R.mipmap.menu_7);
            menuList.add(menuBean3);
            MenuBean menuBean4 = new MenuBean();

//            menuBean4.setCode("smjt");
//            menuBean4.setTitle("扫码交投");
//            menuBean4.setImage(R.mipmap.menu_1);
//            menuList.add(menuBean4);
//
//            MenuBean menuBean5 = new MenuBean();
//            menuBean5.setCode("smqh");
//            menuBean5.setTitle("扫码取货");
//            menuBean5.setImage(R.mipmap.menu_5);
//            menuList.add(menuBean5);
//
//            MenuBean menuBean6 = new MenuBean();
//            menuBean6.setCode("sz");
//            menuBean6.setTitle("设置");
//            menuBean6.setImage(R.mipmap.menu_7);
//            menuList.add(menuBean6);
            SharedPreferencesUtils.setParam(context, "menu_list", gson.toJson(menuList));

        }

    }

    private int TIME = 10000;
    Handler handler = new Handler();

    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            // handler自带方法实现定时器
            try {
                Intent intent = new Intent();
                intent.setAction("com.xinxing.city.guard.heartbeat");
                intent.putExtra("live", true);
                context.sendBroadcast(intent);
                Log.d("DeviceKernel", "向守护进程发送心跳");
                handler.postDelayed(this, TIME);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("exception...");
            }
        }
    };

    @Override
    public ITtsService getTTS() {
        return ttsService;
    }

    private void startGuardApp() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !isRunning(context, "com.xinxing.city.guard.MyService")) {
            SuUtil.start("com.xinxing.city.guard", "com.xinxing.city.guard.MyService", context);
            Log.e("mytest", "---2启动MyServer");
        }
    }

    public static boolean isRunning(Context context, String serviceName) {
        // 获取Activity管理者对象
        ActivityManager manager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        // 获取正在运行的服务（此处设置最多取1000个）
        List<ActivityManager.RunningServiceInfo> runningServices = manager
                .getRunningServices(1000);
        // 遍历，若存在名字和传入的serviceName的一致则说明存在
        for (ActivityManager.RunningServiceInfo runningServiceInfo : runningServices) {
            Log.e("DeviceKernel", "  ---- " + runningServiceInfo.service.getClassName());
            if (runningServiceInfo.service.getClassName().equals(serviceName)) {
                return true;
            }
        }

        return false;
    }
}
